<template>
  <div class="works-list-page">
    <div class="gp-filter">
      <DropDown :list="tagFilter" :value.sync="queryParams.rank" :tlist="tList"
        :subvalue.sync="queryParams.orderByColumn" @change="handleSearch()" style="min-width: 150px;" placeholder="" />
      <div class="seach-bx" :class="{'active':isFocus}">
        <form @submit.prevent="() => { return false }">
          <input type="text" @focus="isFocus = true" @blur="isFocus = false"
            :placeholder="'按标题/风格/类型等搜索 ' + total + ' 个作品'" v-model="queryParams.title" @keypress.enter="handleSearch" />
          <a class="cancel-search" v-if="queryParams.title" @click="queryParams.title=''"></a>
        </form>
      </div>
      <!-- <div class="bs-layout">
        <div class="plat-items">
          <span class="f-layout" :class="{ 'active': model == 'big' }" @click="model = 'big'"></span>
          <span class="mup-layout" :class="{ 'active': model == 'small' }" @click="model = 'small'"></span>
        </div>
      </div> -->
      <div class="bs-g-flabel">
        <span class="cur">筛选</span>
        <div class="games-filter gpic-flt" style="width:546px">
          <div class="games-filter-wrap">
            <div class="gft-data-box" v-for="(item, idx) in filterRows" :key="idx" v-if="item.child.length > 0">
              <div class="tip-top">{{ item.title }}</div>
              <ul class="data-ul">
                <li v-for="(type, i) in item.child" :key="i" @click="chooseRowItem(type)" v-if="type.title != '全部'"><a
                    :class="{ 'active': queryParams.categoryId == type.id }">{{ type.title }}</a></li>
              </ul>
            </div>
            <div class="bot-btns">
              <a class="cancel" @click="handleCancelByGtypeAll">全部取消</a>
              <a class="confirm" @click="handleConfirmByGTypeSearch">确定</a>
            </div>
          </div>
        </div>
      </div>
    </div>
    <ul class="games-data" :class="[model]">
      <li v-for="(item, idx) in list" :key="idx" class="dx-vd-item" :class="{'no-data':!item.id}">
        <a class="fav-d-item" :href="'/work/' + item.id" target="_blank" v-if="item.id">
          <div class="img-flex-box">
            <div class="main-img">
              <img loading="lazy" :srcset="item.srcsets" v-lazy="item.lazy"  @error="loadError"/>
            </div>
            <div class="left-icos">
              <el-popover popper-class="gm-info-pop" placement="top-start" trigger="hover" v-if="item.hot">
                <i class="sm-tip" slot-content>浏览量超2万的热门内容</i>
                <img loading="lazy" slot="reference" src="../../assets/pro/common/hot.png" alt="">
              </el-popover>
            <el-popover popper-class="gm-info-pop" placement="top-start" trigger="hover" v-if='item.new'>
                <i class="sm-tip" slot-content>48小时内发布的最新内容</i>
                <img loading="lazy" slot="reference" src="../../assets/pro/common/new.png" alt="">
            </el-popover>
              <el-popover popper-class="gm-info-pop" placement="top-start" trigger="hover" v-if='item.videoUrl'>
                <i class="sm-tip" slot-content>内容含视频</i>
                <img loading="lazy" slot="reference" src="../../assets/pro/common/video.png" alt="">
              </el-popover>
            </div>
          </div>
          <div class="bot-desc">
            <span class="file-name">{{ item.title }}</span>
          </div>
          <div class="bot-author">
            <a class="u" @click.stop="toUsercenter(item.member.id)">
              <span class="img-box">
                <img loading="lazy" v-aimgd="{ avatar: item.member.avatar, id: item.member.id, w: 20, name: item.member.userName }" />
              </span>
              <span class="name">{{ item.member.userName }}<img loading="lazy" class="u-m-tag" v-for="tag in item.member.tagsList"
                  :src="tag.image" alt=""></span>
            </a>
            <div class="rt">
              <span class="like-num">{{ item.praiseStr }}</span>
              <div class="vnum">
                    {{ item.seeStr }}
                  </div>
            </div>
            </div>
        </a>
      </li>
    </ul>
    <div class="no-more-text" v-if="!hasMore && !isloading && list.length > 0">没有更多了</div>
    <Empty text="没有找到符合条件的结果~" v-if="!isloading && list.length == 0" />

    <div class="pro-bot-loading" v-if="isloading">
        <i class="el-icon-loading"></i>
    </div>

    <el-drawer :with-header="false" destroy-on-close :modal="false" append-to-body :visible.sync="showInfo"
      direction="btt">
      <workInfo @close="onInfoClose" :id="currentId" @prev="onPrev" @next="onNext" />
    </el-drawer>
    <div class="loading-mask" v-if="isloading"></div>
  </div>
</template>

<script>
import Empty from '@/components/Empty'
import DropDown from '@/components/dropdown'
import pswiper from '@/components/pswiper'
import moment from 'moment'
import workInfo from '@/components/workinfo'
import api from '@/api/api'
export default {
  components: { workInfo, pswiper, DropDown, Empty },
  data() {
    return {
      searchIsFocus:false,
      isloading: true,
      tList: [],
      currentIdx: 0,
      tagFilter: [],
      filterRows: [],
      currentId: '',
      gTypesT: ['常用基础', '游戏角色', '游戏内容', '玩家'],
      gTypes: [{ selected: false, title: "标题界面" }, { selected: false, title: "登录注册" }, { selected: false, title: "服务器选择" }, { selected: false, title: "角色创建" }],
      gTypes1: [{ selected: false, title: "主菜单" }, { selected: false, title: "游戏公告" }, { selected: false, title: "关卡选择" }, { selected: false, title: "备战界面" }, { selected: false, title: "大厅" }],
      gTypes2: [{ selected: false, title: "画面" }, { selected: false, title: "声音" }, { selected: false, title: "操作" }, { selected: false, title: "账户" }, { selected: false, title: "其他" }],
      gTypes3: [{ selected: false, title: "转场" }, { selected: false, title: "载入画面" }, { selected: false, title: "进度条" }, { selected: false, title: "加载保存" }, { selected: false, title: "下载进度" }, { selected: false, title: "副本排队" }],
      infoUrlEnum: {
        22: { url: '/game/', name: '游戏' },
        1: { url: '/work/', name: '作品' },
        50: { url: '/video/', name: '短视频' },
        9: { url: '/article/', name: '文章' }
      },
      isFocus: false,
      model: 'small',
      currentId: '',
      showInfo: false,
      keyword: '',
      gTypes: [],
      list: [],
      queryParams: {
        orderByColumn: 'createTime',
        pageSize: 20,
        pageNum: 1,
        isAsc: 'desc',
        rank: '首页推荐',
        categoryId: 1
      },
      total: 0,
      hasMore: true,
      scrollLoaded: false,
      allCates: [],
      curAllCateKey: '',
      curCates: [],
      curFullPath: ''
    }
  },
  destroyed() {
    window.removeEventListener('scroll',this.onscroll)
  },
  async mounted() {
    $('body,html').animate({ scrollTop: 0 }, 300);
    let start = new Date();
    let starttime = moment(start).format('YYYY-MM-DD');
    let end = new Date(start.setDate(start.getDate() + 1));
    let endtime = moment(end).format('YYYY-MM-DD')
    // let res = await api.articlelist({ orderByColumn: 'see', isAsc: 'desc', startTime: starttime, endTime: endtime, pageNum: 1, pageSize: 8 })
    let res = await api.getChildrenListByParentId({ parentId: 1 });
    this.filterRows = res.data;
    res = await api.getCategoryFilter({ type: 'discover' });
    this.tagFilter = res.data.tags.filter(r=>{
      return r.title!='编辑精选'&&r.title!='普通推荐'
    });
    this.tList = res.data.news;

    this.curFullPath = this.$route.fullPath;

    let _gTypes = localStorage.getItem('G-TYPES')
    _gTypes = JSON.parse(decodeURIComponent(_gTypes))
    this.gTypes = _gTypes

    let _allCates = JSON.parse(decodeURIComponent(localStorage.getItem('CATE-ALL-TYPES')))
    this.curAllCateKey = _allCates[1].key
    this.curCates = _allCates[1].result
    this.allCates = _allCates

    let _k=this.$route.query.k;
    if(_k){
        this.queryParams.title=_k;
    }

    this.queryList()
    window.addEventListener('scroll',this.onscroll);
  },
  methods: {
    loadError(e){
        e.target.removeAttribute('srcset');
    },
    onscroll(e){
      let that=this;
      if (that.showInfo) return
      let jHeight = document.documentElement.scrollHeight - document.documentElement.scrollTop - document.documentElement.clientHeight

      if (that.scrollLoaded == false) return
      if (jHeight <= 200 && that.hasMore) {
        if (!localStorage.getItem('token')) {
            that.$parent.$parent.noLoginIsTak = false;
            that.$parent.$parent.showLoginView = true;
            that.isloading = false;
            window.removeEventListener('scroll', that.onscroll);
            return;
        }
        that.scrollLoaded = false;
        that.loadMore();
      }
    },
    handleXClear() {
      this.queryParams = {
        orderByColumn: 'createTime',
        pageSize: 20,
        pageNum: 1,
        isAsc: 'desc',
        rank: '首页推荐',
        categoryId: 1
      }
      this.handleSearch();
    },
    onPrev() {
      if (this.currentIdx == 0) {
        this.$amessage.warn('没有更多了')
        return;
      }
      this.currentIdx--;
      this.currentId = this.list[this.currentIdx].id;
    },
    onNext() {
      if (this.currentIdx == this.list.length - 1) {
        this.$amessage.warn('没有更多了')
        return;
      }
      this.currentIdx++;
      this.currentId = this.list[this.currentIdx].id;
    },
    chooseRowItem(item) {
      this.queryParams.categoryId = this.queryParams.categoryId == item.id ? 1 : item.id;
      this.handleSearch();
    },
    handleCancelByGtypeAll() {
      this.queryParams.categoryId=1;
      this.handleSearch();
     },
    handleConfirmByGTypeSearch() { },
    toUsercenter(id) {
      let routeData = this.$router.resolve({ path: "/user/" + id });
      window.open(routeData.href, '_blank');
    },
    handleSearch(e) {
      if(e)e.target.blur();
      
      window.history.pushState({}, 0,e&&e.target.value?('?t=1&k='+e.target.value):'?t=1');
      this.queryParams.pageNum = 1;
      this.list = [];
      this.scrollLoaded = false;
      this.hasMore = true;
      this.queryList();
    },
    onInfoClose() {
      window.history.pushState({}, 0, this.curFullPath);
      document.body.style.overflow = 'inherit';
      this.showInfo = false;
    },
    handleShowInfo(_item, _idx) {
      this.currentIdx = _idx;
      window.history.pushState({}, 0, '/work/' + _item.id);
      this.currentId = _item.id;
      document.body.style.overflow = 'hidden';
      this.showInfo = true;
    },
    loadMore() {
      this.queryParams.pageNum++
      this.queryList()
    },
    async queryList() {
      var that = this

      this.isloading = true;
      // const loading = this.$loading({
      //   lock: true,
      //   text: '努力加载中...',
      //   spinner: 'el-icon-loading',
      //   background: 'rgba(0, 0, 0, 0.7)'
      // });
      if(that.queryParams.pageNum==1){
        that.list=[{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{}];
      }
      let result = await api.articlelist(that.queryParams);
      if(that.queryParams.pageNum==1){
          that.list=[];
      }
      setTimeout(()=>{
        that.isloading = false;
      },300)

      let old = that.list
      let domainUrl=that.$imgdomainurl;

      result.data.map(item=>{
        let _vtime=null;
        if(item.updateTime){
          _vtime=item.updateTime;
        }else if(item.createTime){
          _vtime=item.createTime;
        }else if(item.create_time){
          _vtime=item.create_time.replace('T',' ');
        }
        _vtime=Math.abs(new Date(_vtime).getTime());
        let srcsets=[];
        srcsets.push(domainUrl+'article-'+item.id+'-'+_vtime+'@1x432.webp 1x');
        srcsets.push(domainUrl+'article-'+item.id+'-'+_vtime+'@2x432.webp 2x');
        srcsets.push(domainUrl+'article-'+item.id+'-'+_vtime+'@3x432.webp 3x');
        item.srcsets=srcsets.join(',')
        item.lazy={
          src:domainUrl+'article-'+item.id+'-'+_vtime+'@1x432.webp',
          error: require('@/assets/l_error_'+(localStorage.getItem('THM-STY')?localStorage.getItem('THM-STY'):'light')+'.png'),
          loading: require('@/assets/l_error_'+(localStorage.getItem('THM-STY')?localStorage.getItem('THM-STY'):'light')+'.png')
        }
      })
      
      that.list = [...old, ...result.data]

      that.total = result.total

      let totalPage = result.total % that.queryParams.pageSize == 0 ? result.total / that.queryParams.pageSize : parseInt(result.total / that.queryParams.pageSize) + 1
      if (result.data && (result.data.length < that.queryParams.pageSize || that.queryParams.pageNum >= totalPage)) {
        that.hasMore = false
      } else {
        that.hasMore = true
      }
      that.scrollLoaded = true
    }
  }
}
</script>

<style lang="less">
.works-list-page {
  // min-height:calc(100vh - 84px - 84px - 44px - 64px);
  .gp-filter {
    position:relative;
    top: 0px;
    padding-bottom: 21px;
    padding-top: 10px;
    margin-bottom: 0px;
    margin-top: 0px;
  }
}

.games-filter-wrap {
  display: flex;
  flex-direction: column;
  grid-gap: 20px;
}
</style>